package com.myorg.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Random;
import java.util.UUID;

import org.apache.http.HttpResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Utility {
	final static private Logger logger = LoggerFactory.getLogger(Utility.class);
	private static Random rdm = new Random();

	public static String getUniqueStrAcrossMultiJVM(String ip) {
		int i = rdm.nextInt(Integer.MAX_VALUE);
		return ip.replace(".", "") + String.valueOf(i);
	}

	public static String measureExecutionTime(Runnable runnable) {
		long start = System.currentTimeMillis();
		runnable.run();
		long end = System.currentTimeMillis();
		long millis = end - start;
		long second = (millis / 1000) % 60;
		long minute = (millis / (1000 * 60)) % 60;
		long hour = (millis / (1000 * 60 * 60)) % 24;
		String time = String.format("%02d:%02d:%02d:%d", hour, minute, second, millis);
		return time;
	}

	public static void profiling(Runnable runnable, String prompt) {
		String metric = measureExecutionTime(runnable);
		logger.info(prompt + metric);
	}

	public static String generateUUID() {
		UUID uniqueID = UUID.randomUUID();
		return String.valueOf(uniqueID);
	}

	public static String readHttpResponse(HttpResponse resp) {
		StringBuilder sb = new StringBuilder();
		try {
			String line = "";
			BufferedReader rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
			while ((line = rd.readLine()) != null) {
				sb.append(line);
			}
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		return sb.toString();
	}
}
